import pandas as pd
from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler

# 读取日志数据
data = pd.read_csv("data.csv")

# 数据处理
result = data.groupby(['src_ip', 'dst_ip', 'dst_port']).size().reset_index(name='count')
print(result)

result['f1'] = 1/(1+result['count'])

# 提取所需的特征变量
# features = data[['外联次数', '连接时长', '包长度']]
features = result[['f1']] 

# 标准化特征变量
scaler = StandardScaler()
scaled_features = scaler.fit_transform(features)

# 使用DBSCAN进行聚类分析
dbscan = DBSCAN(eps=0.3, min_samples=5)
clusters = dbscan.fit_predict(scaled_features)

# 添加聚类结果到原始数据
result['Cluster'] = clusters

# 打印每个簇的统计信息
cluster_counts = result['Cluster'].value_counts()
print(cluster_counts)

# 可以根据需要对聚类结果进行进一步分析和可视化
result.to_csv("dbscan.csv", encoding = 'utf-8')